package com.wh.service.instorehouse;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.api.Api;
import com.wh.mapper.initial.LocationMapper;
import com.wh.mapper.initial.ProductMapper;
import com.wh.mapper.instorehouse.PurchaseMapper;
import com.wh.mapper.instorehouse.ReceivingMapper;
import com.wh.mapper.stock.StockMapper;
import com.wh.mapper.instorehouse.PutInMapper;
import com.wh.mapper.storehousemanage.RemoveMapper;
import com.wh.pojo.*;

import com.wh.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PutInServiceImpl implements PutInService {

    @Autowired
    private PutInMapper putInMapper;

    @Autowired
    private ReceivingMapper receivingMapper;

    @Autowired
    private LocationMapper locationMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RemoveMapper removeMapper;




    @Override
    public Map<String, Object> getQuery(InStorehouse inStorehouse) {
        Purchase purchase = new Purchase();
        if (StringUtils.hasLength(inStorehouse.getReceivingId())){
            Receiving receivingAble = receivingMapper.selectById(inStorehouse.getReceivingId());
            purchase = purchaseMapper.selectById(receivingAble.getPurchaseId());
        }

        QueryWrapper<Receiving> receivingQueryWrapper = new QueryWrapper<>();
        receivingQueryWrapper.eq("status","已审核")
                .select("receiving_id");


        QueryWrapper<Location> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.eq("status","空闲")
                .eq("type","入库区")
                .eq(StringUtils.hasLength(purchase.getStorehouse()),"storehouse",purchase.getStorehouse())
                .select("location_id");

        List<Receiving> receivingList = receivingMapper.selectList(receivingQueryWrapper);
        List<Location> locationList = locationMapper.selectList(locationQueryWrapper);

        List<String> receivingIdList = new ArrayList<>();
        List<String> locationIdList = new ArrayList<>();

        for (Receiving receiving : receivingList){
            receivingIdList.add(receiving.getReceivingId());
        }

        if (locationList != null){
            for (Location location : locationList){
                locationIdList.add(location.getLocationId());
            }
        }


        Map<String,Object> map = new HashMap<>();
        map.put("receivingIdList",receivingIdList);
        map.put("locationIdList",locationIdList);

        return map;
    }

    @Override
    public String addInStorehouse(InStorehouse inStorehouse) {
        QueryWrapper<InStorehouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("location_id",inStorehouse.getLocationId());
        if(putInMapper.selectCount(queryWrapper) != 0){
            return "已有记录";
        }
        inStorehouse.setStatus("待审核")
                .setInStorehouseId("IN" + System.currentTimeMillis())
                .setCreateTime(new Api().getTime());
        putInMapper.insert(inStorehouse);
        Receiving receiving = receivingMapper.selectById(inStorehouse.getReceivingId());
        receiving.setStatus("进行中");
        receivingMapper.updateById(receiving);
        return "添加成功";
    }

    @Override
    public PageResult getInStorehouseList(PageResult pageResult) {
        Page<InStorehouse> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());

        boolean flag = StringUtils.hasLength(pageResult.getQuery());

        QueryWrapper<InStorehouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(flag,"in_storehouse_id",pageResult.getQuery());

        page = putInMapper.selectPage(page,queryWrapper);

        pageResult.setTotal((long) page.getRecords().size()).setRows(page.getRecords());


        return pageResult;
    }


    @Override
    //
    public void updataInStorehouse(InStorehouse inStorehouse) {
        //判断订单状态
        if (inStorehouse.getStatus().equals("已审核")){
            //设置审核时间
            inStorehouse.setCheckTime(new Api().getTime());
            check(inStorehouse);
        }else if(inStorehouse.getStatus().equals("待审核")){
            inStorehouse.setCheckTime("")
                    .setCheckPerson("");
            stockMapper.deleteById(inStorehouse.getLocationId());

            Location location = locationMapper.selectById(inStorehouse.getLocationId());
            location.setStatus("空闲");
            locationMapper.updateById(location);

        }
        putInMapper.updateById(inStorehouse);
    }

    @Override
    public String deleteInStorehouse(String inStorehouseId, String receivingId) {
        Receiving receiving = receivingMapper.selectById(receivingId);
        receiving.setStatus("已审核");
        receivingMapper.updateById(receiving);
        putInMapper.deleteById(inStorehouseId);
        return "撤销成功";
    }



    public void check(InStorehouse inStorehouse){
        Stock stock = new Stock();

        //获取货位名称
        Location location = locationMapper.selectById(inStorehouse.getLocationId());
        String locationName = location.getName();

        //获取商品条码
        String barCode = null;
        //获取接货单
        Receiving receiving = receivingMapper.selectById(inStorehouse.getReceivingId());
        if (StringUtils.hasLength(receiving.getPurchaseId())) {
            Purchase purchase = purchaseMapper.selectById(receiving.getPurchaseId());
            barCode = purchase.getBarCode();
            stock.setTotalQuantity(purchase.getCount())
                .setAvailableQuantity(purchase.getCount());
        } else {
            Remove remove = removeMapper.selectById(receiving.getRemoveId());
            barCode = remove.getBarCode();
            stock.setTotalQuantity(remove.getCount())
                    .setAvailableQuantity(remove.getCount());
        }

        //获取商品名称
        Product product = productMapper.selectById(barCode);
        String productName = product.getName();

        //赋值
        stock.setInStorehouseId(inStorehouse.getInStorehouseId())
                .setLocationId(inStorehouse.getLocationId())
                .setLocationName(locationName)
                .setBarCode(barCode)
                .setProductName(productName)
                .setLockedQuantity(0)
                .setStatus("待上架");

        stockMapper.insert(stock);

        //修改移库源货位库存
        if (receiving.getRemoveId() != null){
            Remove remove = removeMapper.selectById(receiving.getRemoveId());
            Stock fromStock = stockMapper.selectById(remove.getFromLocationId());
            fromStock.setLockedQuantity(fromStock.getLockedQuantity() - remove.getCount())
                    .setTotalQuantity(fromStock.getTotalQuantity() - remove.getCount());
            stockMapper.updateById(fromStock);

        }


        location.setStatus(barCode);
        locationMapper.updateById(location);

    }


}
